package com.example;

import com.example.utils.ConnectionFactoryUtils;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangxiyuan
 * @description
 * @createDate 2021/3/29 19:25
 **/
public class DelayQueueProducer {
    // 队列名称
    private final static String EXCHANGE_NAME="delay_exchange";
    private final static String ROUTING_KEY="key_delay";

    @SuppressWarnings("deprecation")
    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = ConnectionFactoryUtils.getConnectionFactory();
        try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

            // 声明x-delayed-type类型的exchange
            Map<String, Object> args = new HashMap<String, Object>();
            // 这里声明交换器的类型
            args.put("x-delayed-type", "direct");
            channel.exchangeDeclare(EXCHANGE_NAME, "x-delayed-message", true,
                    false, args);


            Map<String, Object> headers = new HashMap<String, Object>();

            String readyToPushContent = "publish at " + sf.format(new Date())
                    + " \t deliver at 5000";
            System.out.println(readyToPushContent);
            headers.put("x-delay", 5000);

            AMQP.BasicProperties.Builder props = new AMQP.BasicProperties.Builder()
                    .headers(headers);
            channel.basicPublish(EXCHANGE_NAME, "xxxx", props.build(),
                    readyToPushContent.getBytes());
        }
    }
}
